<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商店名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商店名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商店电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入商店电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.shop_business_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
    </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:store:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:store:edit']"
        >修改</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['shop:store:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['shop:store:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" highlight-current-row @current-change="handleSelectionChange">
      <el-table-column type="index" width="55" align="center" />
<!--      <el-table-column label="商店id" align="center" prop="id" />-->
      <el-table-column label="商店名称" align="center" prop="name" />
      <el-table-column label="商店电话" align="center" prop="phone" />
      <el-table-column label="开店时间" align="center" prop="openDate" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.openDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐指数" align="center" prop="recValue" />
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :options="dict.type.shop_business_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:store:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status === '1'"
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleCenters(scope.row)"
            v-hasPermi="['shop:store:centers']"
          >关联自提点</el-button>
          <el-button
            v-if="scope.row.status === '1'"
            size="mini"
            type="text"
            icon="el-icon-goods"
            @click="handleGoods(scope.row)"
            v-hasPermi="['shop:goods:list']"
          >商品管理</el-button>
          <el-button
            v-show="scope.row.status === '2'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:store:remove']"
          >删除</el-button>
          <el-dropdown
            v-if="scope.row.status === '2'"
            size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleCenters" icon="el-icon-link"
                                v-hasPermi="['system:user:edit']">关联自提点</el-dropdown-item>
              <el-dropdown-item command="handleGoods" icon="el-icon-goods"
                                v-hasPermi="['system:user:edit']">商品管理</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文创商店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺信息" prop="sysStoresId">
          <el-select
            v-model="form.sysStoresId"
            filterable
            remote
            reserve-keyword
            default-first-option
            style="width: 100%"
            placeholder="请输入店铺名称检索"
            :remote-method="getSysStoresList"
            :loading="sysStoresLoading">
            <el-option
              v-for="item in sysStoresOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商店名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商店名称" />
        </el-form-item>
        <el-form-item label="商店描述" prop="storeDesc">
          <el-input v-model="form.storeDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商店地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入商店地址" />
        </el-form-item>
        <el-form-item label="商店电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入商店电话" :maxlength="13"/>
        </el-form-item>
        <el-form-item label="开店时间" prop="openDate">
          <el-date-picker clearable
            v-model="form.openDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开店时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="推荐指数" prop="recValue" v-hasPermi="['shop:store:rec']">
          <el-input v-model="form.recValue" placeholder="请输入推荐指数" maxlength="4"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.shop_business_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="centersOpen" width="700px" append-to-body>
      <el-transfer
        style="text-align: left; display: inline-block"
        v-model="mapList"
        filterable
        :titles="['自提点列表', '已关联列表']"
        :button-texts="['移除', '添加']"
        :format="{
        noChecked: '${total}',
        hasChecked: '${checked}/${total}'
      }"
        @change="transferChange"
        :data="goodsCentersList">
        <span slot-scope="{option}">{{ option.label }}</span>
<!--        <span slot-scope="{ option }">{{ option.key }} - {{ option.label }}</span>-->
<!--        <el-button class="transfer-footer" slot="left-footer" size="small">操作</el-button>-->
<!--        <el-button class="transfer-footer" slot="right-footer" size="small">操作</el-button>-->
      </el-transfer>
    </el-dialog>
  </div>
</template>

<script>
import { listStore, getStore, delStore, addStore, updateStore } from "@/api/shop/store";
import { listStoreCenters, delStoreCenters, addStoreCenters } from "@/api/shop/storeCenters";
import { listGoodsCenters } from "@/api/shop/goodsCenters";
import { listStoresByDS } from "@/api/system/stores";

export default {
  name: "Store",
  dicts: ['shop_business_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组名称
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文创商店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示自提点弹出层
      centersOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
      },
      // 表单参数
      form: {},
      // 自提点列表
      goodsCentersList: [],
      // 已关联自提点列表
      mapList: [],
      storeId: '',
      // 表单校验
      rules: {
        name: [
          { required: true, trigger: "blur", message: "请输入商店名称" }
        ],
        sysStoresId: [
          { required: true, trigger: "blur", message: "请选择店铺信息" }
        ],
      },
      // 商店数据源
      sysStoresOptions: [],
      // 商店选择遮罩
      sysStoresLoading: false
    };
  },
  created() {
    this.getList();
    this.getSysStoresList();
  },
  methods: {
    /** 查询文创商店列表 */
    getList() {
      this.loading = true;
      listStore(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询基本店铺列表 */
    getSysStoresList(query) {
      if (query !== '') {
        this.sysStoresLoading = true;
        const queryParams = {
          name: query
        }
        listStoresByDS(queryParams).then(response => {
          this.sysStoresOptions = response.rows;
          this.sysStoresLoading = false;
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sysStoresId: null,
        name: null,
        storeDesc: null,
        address: null,
        phone: null,
        openDate: null,
        recValue: null,
        status: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection === null) {
        this.single = true
      } else {
        this.ids = selection.id
        this.names = selection.name
        this.single = false
      }
      // this.ids = selection.map(item => item.id)
      // this.names = selection.map(item => item.name)
      // this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文创商店";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStore(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文创商店";
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleCenters":
          this.handleCenters(row);
          break;
        case "handleGoods":
          this.handleGoods(row);
          break;
        default:
          break;
      }
    },
    /** 关联自提点操作 */
    handleCenters(row) {
      const queryParams = {
        pageNum: 1,
        pageSize: 100
      }
      // 查询自提点
      listGoodsCenters(queryParams).then(response => {
        const d = []
        response.rows.forEach(e =>{
          d.push({
            key: e.id,
            label: e.address
          });
        })
        this.goodsCentersList = d;
        const queryMapParams = {
          pageNum: 1,
          pageSize: 100,
          storeId: row.id
        }
        // 查询已关联的自提点
        listStoreCenters(queryMapParams).then(response => {
          const d = []
          response.rows.forEach(e =>{
            d.push(e.centersId);
          })
          this.mapList = d;
          this.centersOpen = true;
          this.title = "关联自提点";
          this.storeId = row.id
        });
      });
    },
    /** 穿梭框修改事件 */
    transferChange(value, direction, movedKeys){
      if (direction === 'left') {
        const data = {
          storeId: this.storeId,
          centersIds: movedKeys
        }
        delStoreCenters(data).then(response => {
          this.$modal.msgSuccess(response.msg);
        });
      } else if (direction === 'right') {
        const data = {
          storeId: this.storeId,
          centersIds: movedKeys
        }
        addStoreCenters(data).then(response => {
          this.$modal.msgSuccess(response.msg);
        });
      }
    },
    /** 商品管理按钮操作 */
    handleGoods(row) {
      const params = {storeId: row.id};
      this.$tab.openPage("[" + row.name + "]商品管理", '/shop/goods/goods', params);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStore(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStore(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.name || this.names;
      this.$modal.confirm('是否确认删除【' + names + '】商店？').then(function() {
        return delStore(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shop/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
